﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ThreadQuery
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            int threadCount = 0;
            int queryCount = 0;

            if (!int.TryParse(txtThreads.Text, out threadCount))
            {
                MessageBox.Show("请输入正确的线程数！");
                return;
            }

            if (!int.TryParse(txtQuery.Text, out queryCount))
            {
                MessageBox.Show("请输入正确的请求数！");
                return;
            }

            btnExec.Enabled = false;
            rTxtMsg.Text = string.Empty;

            startTestThreads("", threadCount, queryCount);
        }

        private void startTestThreads(string cmd,int threadCount, int queryCount)
        {
            QueryProcess process = new QueryProcess(cmd, threadCount, queryCount, chkIsBlock.Checked);
            process.Completed += process_Completed;
            process.ProcessChanged += process_ProcessChanged;
            process.NewLog += process_NewLog;
            process.Exec();
        }

        void process_NewLog(object sender, EventArgs<string> e)
        {
            AppendMessage(e.Value);
        }

        void process_ProcessChanged(object sender, EventArgs<ProcessInfo> e)
        {
            int curr = (int)(((float)e.Value.Current / e.Value.Total) * 100);
            changeProgress(curr);
        }

        void process_Completed(object sender, EventArgs e)
        {
            AppendMessage("测试请求完成");
            btnExec.Enabled = true;
            //this.btnExec.Invoke((MethodInvoker)delegate() { btnExec.Enabled = true; });
        }

        public void AppendMessage(string msg)
        {
            this.rTxtMsg.Invoke((MethodInvoker)delegate() { rTxtMsg.AppendText(msg); });
        }

        public void changeProgress(int value)
        {
            progressBar1.Invoke((MethodInvoker)delegate() { progressBar1.Value = value; });
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            txtQuery.Text = "100";
            txtThreads.Text = "10";
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        //public void updateStatusText(string txt)
        //{
        //    this.tsStatus.Text = txt;
        //}
    }
}
